package com.example.interceptor;

import com.example.config.BaseContext;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 只能写 /* 如果写的是 /** doFilter方法是没法执行的
@WebFilter(filterName="myFilter",urlPatterns={
        "/*"
//        "/user/*"
})
@Order(1) // filter顺序 越小越在前
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter被初始化。。。");
    }

    @Override
    public void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {

        System.out.println("进入Filter");

        HttpServletRequest request = (HttpServletRequest) servletRequest ;

        HttpServletResponse response = (HttpServletResponse) servletResponse ;

        String uri = request.getRequestURI();

        Long empId = (Long) request.getSession().getAttribute("employee");

        if (uri.equals("/user/setLocal") || empId!=null){
            if(empId!=null){
                BaseContext.setCurrentId(empId);
            }
            filterChain.doFilter(request, response);
        }
        System.out.println("离开Filter");
    }

    @Override
    public void destroy() {
        System.out.println("Filter被销毁了!!");
        BaseContext.remove();
    }
}
